﻿using UnityEngine;
using System;
using System.Collections;

public class CameraController : Singleton<CameraController> {
	public float TargetAngleX		= 0f;
	public float AngleY 			= 45f;
	public float TargetDistance 	= 10f;
	public float rotationVelocity	= 0.0f;
	public float distanceVelocity	= 0.0f;
	public float smooth 			= 0.3f;
	public Vector3 targetPosition	= Vector3.zero;

	private GameObject _target		= null;
	private float _angleX 			= 0f;
	private float _distance 		= 10f;

	// Use this for initialization
	void Start () {
		_target = new GameObject ();
		_target.name = "CameraTarget";
		_target.transform.position = targetPosition;
	}
	
	// Update is called once per frame
	void Update () {
		_angleX = Mathf.SmoothDampAngle(_angleX, TargetAngleX, ref rotationVelocity, smooth);
		_distance = Mathf.SmoothDampAngle(_distance, TargetDistance, ref distanceVelocity, smooth);

		Vector3 position = transform.position;
		position.z = targetPosition.z - Mathf.Cos (Mathf.Deg2Rad * _angleX) * _distance;
		position.y = targetPosition.y + Mathf.Cos (Mathf.Deg2Rad * AngleY) * _distance;
		position.x = targetPosition.x - Mathf.Sin (Mathf.Deg2Rad * _angleX) * _distance;
		transform.position = position;
		transform.LookAt (targetPosition);
		_target.transform.LookAt (new Vector3(transform.position.x, 0, transform.position.z));
	}

	public void Rotate(float rotationDistance) {
		if (TargetAngleX + (rotationDistance * smooth) > 360) {
			TargetAngleX = 360 - TargetAngleX;
		} else {
			TargetAngleX += (rotationDistance * smooth);
		}
	}

	public void Pan(Vector3 moveBy) {
		_target.transform.Translate (moveBy, Space.Self);
		targetPosition = _target.transform.position;
	}

	public void Zoom(float moveDistance) {
		TargetDistance -= (moveDistance * 5);
	}
}
